<template>
  <view class="pageLayout">
    <u--form
      labelPosition="left"
      :model="form"
      :rules="rules"
      ref="MyForm"
      labelWidth="150rpx"
      :labelStyle="labelStyle"
    >
      <view class="base_info">
        <u-form-item
          label="客户收取区号"
          prop="designerName"
          borderBottom
          @click="showPhonePicker = true"
        >
          <multiPicker
            :value="phonePrefixInfo"
            :list="countryList"
            :show.sync="showPhonePicker"
            title="请选择"
            :show-search="true"
            key-name="label"
            id-name="code"
            :inputAlign="'right'"
            @confirm="handlePhoneConfirm"
            :showIcon="false"
            :multiselect="false"
          />
        </u-form-item>
        <u-form-item
          label="客户联系方式"
          prop="customerPhoneNumber"
          borderBottom
        >
          <u--input
            placeholder="请输入手机号"
            :inputAlign="inputAlign"
            :fontSize="fontSize"
            v-model="form.customerPhoneNumber"
            border="none"
          ></u--input>
        </u-form-item>
        <u-form-item prop="appNumber" borderBottom>
          <u--input
            placeholder="请输入APP账号(如：微信号)"
            :inputAlign="inputAlign"
            :fontSize="fontSize"
            v-model="form.appNumber"
            border="none"
          ></u--input>
        </u-form-item>
        <u-form-item
          label="SA分级"
          prop="matchCustomerSourceLevel"
          @click="showLevelPicker = true"
          borderBottom
        >
          <myPicker
            :list="LevelList"
            :show.sync="showLevelPicker"
            @close="closeNotPicker"
            keyName="label"
            v-model="form.matchCustomerSourceLevel"
            idName="value"
            :inputAlign="'right'"
            :iconSize="'24rpx'"
            :fontSize="'24rpx'"
            @confirm="changeLink"
            placeholder="请选择评级"
            :showIcon="false"
          ></myPicker>
        </u-form-item>
        <u-form-item label="面积" prop="area" borderBottom>
          <u--input
            placeholder="请输入面积"
            :inputAlign="inputAlign"
            :fontSize="fontSize"
            v-model="form.area"
            border="none"
          ></u--input>
        </u-form-item>
        <u-form-item label="户型" prop="houseType" borderBottom>
          <u--input
            placeholder="请输入户型"
            :inputAlign="inputAlign"
            :fontSize="fontSize"
            v-model="form.houseType"
            border="none"
          ></u--input>
        </u-form-item>
        <u-form-item label="预算" prop="budget" borderBottom>
          <u--input
            placeholder="请输入预算"
            :inputAlign="inputAlign"
            :fontSize="fontSize"
            v-model="form.budget"
            border="none"
          ></u--input>
        </u-form-item>
        <u-form-item label="风格" prop="style" borderBottom>
          <u--input
            placeholder="请输入风格"
            :inputAlign="inputAlign"
            :fontSize="fontSize"
            v-model="form.style"
            border="none"
          ></u--input>
        </u-form-item>
        <u-form-item
          label="是否来佛"
          prop="comeType"
          @click="showComeType = true"
          borderBottom
        >
          <myPicker
            :list="comelList"
            :show.sync="showComeType"
            @close="closeNotPicker"
            keyName="label"
            v-model="form.comeType"
            idName="value"
            :inputAlign="'right'"
            :iconSize="'24rpx'"
            :fontSize="'24rpx'"
            @confirm="changeComeType"
            placeholder="请选择是否来佛"
            :showIcon="false"
          ></myPicker>
        </u-form-item>
        <u-form-item
          label="来佛月份"
          prop="comeTime"
          borderBottom
          @click="
            showYearMonthPicker = true;
            timeKey = 'comeTime';
          "
          v-if="form.comeType === 'Come'"
        >
          <u--input
            v-model="form.comeTime"
            border="none"
            disabled
            disabledColor="#ffffff"
            placeholder="请选择使用日期"
            :inputAlign="inputAlign"
            :fontSize="fontSize"
          ></u--input>
          <u-icon
            slot="right"
            name="arrow-right"
            :color="color"
            :customStyle="arrowRightStyle"
          ></u-icon>
        </u-form-item>
        <u-form-item
          label="下次跟进时间"
          prop="nextFollowUpTime"
          borderBottom
          @click="
            showDatePicker = true;
            timeKey = 'nextFollowUpTime';
          "
          v-if="userInfo.enterpriseID === '1' && type == 'record'"
        >
          <u--input
            v-model="form.nextFollowUpTime"
            border="none"
            disabled
            disabledColor="#ffffff"
            placeholder="请选择使用日期"
            :inputAlign="inputAlign"
            :fontSize="fontSize"
          ></u--input>
          <u-icon
            slot="right"
            name="arrow-right"
            :color="color"
            :customStyle="arrowRightStyle"
          ></u-icon>
        </u-form-item>

        <u-form-item labelPosition="top" prop="remark">
          <view class="labelStyle" style="font-size: 24rpx">需求备注</view>
          <u--textarea
            v-model="form.remark"
            border="none"
            height="50"
            placeholder="例：跟进情况、客户需求、服务需求或者细节"
          ></u--textarea>
        </u-form-item>
      </view>
      <view class="base_info">
        <u-form-item labelPosition="top" @click="showPicker = true">
          <view class="labelStyle" style="font-size: 24rpx">标签记录</view>
          <tagPicker
            :value="selectedItems"
            :list="tagList"
            :show.sync="showPicker"
            title="请选择标签"
            :show-search="true"
            @confirm="handleTagConfirm"
            :iconSize="'20rpx'"
            :fontSize="'20rpx'"
            :showIcon="false"
            :showSearch="false"
            @addTag="addTag"
          />
        </u-form-item>
      </view>
    </u--form>
    <view class="btn_width">
      <u-button
        class="btn"
        :loading="loading"
        @click="submitForm"
        size="small"
        shape="circle"
        color="#a22d27"
        customStyle="margin-left: 20rpx;padding:8rpx 22rpx;border:1rpx solid #A22C26;color: #ffffff;font-weight:700;"
        >确定</u-button
      >
    </view>
    <u-datetime-picker
      :show="showDatePicker"
      v-model="Date"
      mode="date"
      @confirm="changeDatePicker"
      @cancel="showDatePicker = false"
      :minDate="todayTimestamp"
      :immediateChange="true"
    ></u-datetime-picker>
    <u-datetime-picker
      :show="showYearMonthPicker"
      v-model="dateYearMonth"
      mode="year-month"
      @confirm="changeYearPicker"
      @cancel="showYearMonthPicker = false"
      :minDate="todayTimestamp"
      :immediateChange="true"
    ></u-datetime-picker>
    <mytoast ref="toastRef" />
  </view>
</template>

<script>
import store from "../../store/index";
import myPicker from "@/components/myPicker";
import tagPicker from "@/components/tagPicker";
import mytoast from "@/components/mytoast.vue";
import multiPicker from "@/components/multiPicker";
import {
  getCustomerTagByID,
  addCustomerResourceTags,
} from "@/api/customer/index";
import countryList from "@/utils/countryList.js";
export default {
  components: {
    myPicker,
    tagPicker,
    mytoast,
    multiPicker,
  },
  data() {
    return {
      countryList,
      Date: null,
      id: "",
      dateYearMonth: null,
      showYearMonthPicker: false, //年月选择器
      showLinkPicker: false, //链接状态
      showLinkTypePicker: false, //链接类型
      showServiceTypePicker: false, //服务类型
      showLevelPicker: false, //SA分级
      showNotPicker: false, //签约结果
      showPicker: false, //
      showDatePicker: false, //日期选择器
      showComeType: false, //是否来佛
      showPhonePicker: false, //客户手机区号
      isFillIn: false,
      loading: false,
      type: "",
      hasName: "",
      timeKey: "",
      tagList: [
        { name: "需跟进", id: "需跟进", customerResourceTagLevel: "Record" },
        { name: "已添加微信", id: "已添加微信", key: "hasWeChat" },
        { name: "高意向", id: "高意向", key: "isHignIntention" },
        { name: "无效客资", id: "无效客资", key: "isInvalid" },
      ], // 标签列表
      labelStyle: {
        "font-size": "24rpx",
      },
      fontSize: "24rpx",
      inputAlign: "right",
      phonePrefixInfo: [
        {
          country: "中国大陆",
          code: "+86",
          label: "中国大陆+86",
        },
      ],
      form: {
        appNumber: "",
        customerPhoneNumber: "",
        hasLink: "",
        linkType: "",
        serviceType: "",
        matchCustomerSourceLevel: "",
        comeType: "",
        comeTime: "",
        remark: "",
        area: "",
        houseType: "",
        areaUnit: "",
        budget: "",
        style: "",
        customerResourceState: "",
        tagType: "",
      },
      todayTimestamp: "",
      selectedItems: [],
      hasLinkList: [
        // 是否已拍链接
        {
          label: "已拍链接",
          value: true,
        },
        {
          label: "未拍链接",
          value: false,
        },
      ],
      serviceTypeList: [
        // 服务类型
        {
          label: "线上代买",
          value: "OnLineShipping",
        },
        {
          label: "线下带看",
          value: "OfflineViewing",
        },
      ],
      LevelList: [
        // 客户等级
        {
          label: "S",
          value: "S",
        },
        {
          label: "A",
          value: "A",
        },
        {
          label: "B",
          value: "B",
        },
        {
          label: "C",
          value: "C",
        },
        {
          label: "D",
          value: "D",
        },
        {
          label: "未分配",
          value: "None",
        },
      ],
      linkTypeList: [
        // 链接类型
        {
          label: "1000链接",
          value: "OneThousand",
        },
        {
          label: "5000链接",
          value: "FiveThousand",
        },
      ],
      comelList: [
        // 链接类型
        {
          label: "来",
          value: "Come",
        },
        {
          label: "不来",
          value: "NotCome",
        },
        {
          label: "不清楚",
          value: "UnClear",
        },
      ],
      rules: {
        appNumber: [
          {
            type: "string",
            required: false,
            // message: "请填写客户联系方式（二选一)",
            trigger: ["blur", "change"],
            validator: (rule, value, callback) => {
              if (
                this.hasName &&
                (value == "" || value == null) &&
                (this.form.customerPhoneNumber == "" ||
                  this.form.customerPhoneNumber == null)
              ) {
                console.log(this.hasName, "hasName");
                // return false;
                callback(new Error("请填写客户联系方式。如：微信号（二选一)"));
              }
              return callback();
            },
          },
        ],
        customerPhoneNumber: [
          {
            type: "string",
            required: false,
            message: "请输入正确手机号",
            trigger: ["blur", "change"],
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // uni.$u.test.amount()就是返回true或者false的

              if (
                this.hasName &&
                (value == "" || value == null) &&
                (this.form.appNumber == "" || this.form.appNumber == null)
              ) {
                console.log(this.hasName);
                // return false;
                callback(new Error("请填写客户联系方式（二选一)"));
              } else if (value) {
                return uni.$u.test.mobile(value);
              } else {
                callback();
              }
            },
          },
        ],
        area: [
          {
            type: "string",
            required: false,
            message: "请输入正确面积",
            trigger: ["blur", "change"],
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // uni.$u.test.amount()就是返回true或者false的
              if (value == "" || value == null) {
                callback();
              }
              return uni.$u.test.amount(value);
            },
          },
        ],
        houseType: [
          {
            type: "string",
            required: false,
            message: "请输入户型",
            trigger: ["blur", "change"],
          },
        ],
        comeTime: [
          {
            type: "string",
            required: false,
            message: "请选择来佛时间",
            trigger: ["blur", "change"],
          },
        ],
        // nextFollowUpTime: [
        //   {
        //     type: "string",
        //     required: true,
        //     message: "请选择下次跟进时间",
        //     trigger: ["blur", "change"],
        //   },
        // ],
        remark: [
          {
            type: "string",
            required: false,
            message: "请输入需求备注",
            trigger: ["blur", "change"],
          },
        ],

        budget: [
          {
            type: "string",
            required: false,
            message: "请输入预算",
            trigger: ["blur", "change"],
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // uni.$u.test.amount()就是返回true或者false的
              if (value == "" || value == null) {
                callback();
              }
              return uni.$u.test.amount(value);
            },
          },
        ],
      },
    };
  },
  computed: {
    hasLogin() {
      return this.$store.state.token && this.$store.state.token.length > 0;
    },
  },
  methods: {
    /**
     * 获取手机区号
     */
    handlePhoneConfirm(val) {
      console.log(val, "handlePhoneConfirm");
      this.phonePrefixInfo = val;
    },
    /**
     * 获取当天和后天零点时间戳
     * @param {boolean} isUTC 是否使用UTC时间
     * @returns { todayZero: number, afterTomorrowZero: number }
     */
    getZeroTimestamps(isUTC = false) {
      const getZeroDate = () => {
        const date = new Date();

        date.setHours(0, 0, 0, 0);
        return date;
      };

      // 当天零点
      const todayZero = getZeroDate().getTime();

      // 明天零点
      const afterTomorrowDate = getZeroDate();
      afterTomorrowDate.setDate(afterTomorrowDate.getDate() + 1);
      const afterTomorrowZero = afterTomorrowDate.getTime();

      return { todayZero, afterTomorrowZero };
    },
    /**
     * 获取时间选择范围
     */
    getDateSele() {
      const { todayZero, afterTomorrowZero } = this.getZeroTimestamps();
      this.todayTimestamp = todayZero;
      // this.MaxTimestamp = afterTomorrowZero;
      this.Date = todayZero;
    },
    /**
     * 日期选择
     */
    changeDatePicker(val) {
      console.log(val, "date");
      let date;
      date = this.formatTimestamp(val.value, "onlyDate");
      this.form[this.timeKey] = date;
      this.showDatePicker = false;
      console.log(this.form);
    },
    /**
     * 年月选择
     */
     changeYearPicker(val) {
      console.log(val, "year-month");
      let date = this.formatTimestamp(val.value, "month");
      this.form[this.timeKey] = date;
      this.showYearMonthPicker=false;
    },
    /**
     * 标签选择回调
     * @param value 选择的标签
     */
    handleTagConfirm(value) {
      console.log(value, "handleTagConfirm");
      let keyList = [];
      value.forEach((item) => {
        if (item.hasOwnProperty("key")) {
          keyList.push(item.key);
        }
      });
      this.tagList.map((item) => {
        if (!keyList.includes(item.key)) {
          this.form[item.key] = false;
        }
      });
      console.log(keyList, "keyList");

      this.selectedItems = value;
    },
    /**
     * 自定义标签添加
     * @param value 添加的标签
     */
    addTag(value, selected) {
      console.log(value, selected, "addTag");
      let obj = {
        name: value.tag,
        id: value.tag,
        customerResourceTagLevel: value.customerResourceTagLevel,
      };
      let arr = selected;
      this.tagList.push(obj);
      this.selectedItems = [...arr, obj];
    },
    /**
     * 链接状态
     */
    changeLink(val) {
      console.log(val, "changeLink");
    },
    /**
     * 是否来佛
     */
    changeComeType(val) {
      console.log(val, "changeLink");
      this.form.comeTime = "";
    },
    /**
     * 获取客户信息
     */
    getInfo() {
      getCustomerTagByID({ customerResourceID: this.id }).then((res) => {
        console.log(res.data, "res.data");
        this.form = res.data;
        let tagArr = this.form.listThreeLevelTag.map((item) => {
          let hastag = this.tagList.find((tag) => tag.name === item.tag);

          let tag = {
            name: item.tag,
            id: item.tag,
            customerResourceTagLevel: item.customerResourceTagLevel,
          };
          if (!hastag || hastag == undefined) {
            this.tagList.push(tag);
          }
          return tag;
        });
        this.selectedItems = tagArr;
        this.tagList.map((item) => {
          if (
            item.hasOwnProperty("key") &&
            this.form.hasOwnProperty([item.key])
          ) {
            if (this.form[item.key]) {
              this.selectedItems.push(item);
            }
          }
        });
      });
    },
    /**
     * 表单提交
     */
    async submitForm() {
      console.log(this.$refs.MyForm, "this.form");
      let action = await this.$refs.MyForm.validate();
      if (this.type == "record") {
        this.form.tagType = "FollowUp";
      } else {
        this.form.tagType = "Update";
      }
      if (action) {
        let tagArr = [];
        this.selectedItems.map((item) => {
          if (item.hasOwnProperty("key")) {
            this.form[item.key] = true;
          } else {
            let val = {
              tag: item.name,
              customerResourceTagLevel: item.customerResourceTagLevel,
            };
            tagArr.push(val);
          }
        });
        this.form.listThreeLevelTag = tagArr;
        this.form.phonePrefix = this.phonePrefixInfo[0].code;
        this.form.phoneCountry = this.phonePrefixInfo[0].country;
        console.log(this.form, "this.form");

        // return;
        addCustomerResourceTags(this.form)
          .then((res) => {
            console.log(res, "res8848");
            uni.showToast({ title: "修改成功", icon: "none" });
            uni.navigateBack();
          })
          .catch((e) => {
            console.log(e.data, "e8848");

            this.$refs.toastRef.showToast({
              msg: e.data.detail,
              duration: 3000,
              position: "center",
            });
          });
        console.log(this.form, "this.form");
      } else {
        uni.showToast({ title: "请完善表单", icon: "none" });
        return false;
      }
    },
    /**
     * 未签约原因选择器
     */
    closeNotPicker() {
      this.$nextTick(() => {
        this.showNotPicker = false;
        this.showLinkPicker = false;
        this.showLinkTypePicker = false;
        this.showServiceTypePicker = false;
        this.showLevelPicker = false;
        this.showComeType = false;
        this.showPhonePicker = false;
      });
    },
    /**
     * 标签选择器
     */
    handleConfirm(val) {
      this.$nextTick(() => {
        this.showPicker = false;
      });
    },
  },
  onLoad(options) {
    this.id = options.id;
    this.hasName = options.hasName;
    this.type = options.type;
    this.getInfo();
  },
  onShow() {
    this.getDateSele();
    console.log(this.countryList);
    console.log(this.userInfo);
  },
  onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.MyForm.setRules(this.rules);
  },
  /**
   * 上拉加载更多
   */
  onReachBottom() {},
};
</script>
<style>
page {
  background-color: #f5f7fb;
}
</style>

<style lang="scss" scoped>
.pageLayout {
  padding: 40rpx;
}
.base_info {
  background-color: #ffffff;
  padding: 24rpx;
  box-sizing: border-box;
  border-radius: 8rpx;
  margin-bottom: 24rpx;
}
.labelStyle {
  margin-bottom: 24rpx;
}
.submit-container {
  margin-top: 40rpx;
  padding: 20rpx;
  background-color: #f5f7fb;
}
.btn_width {
  width: 60%;
  margin: 60rpx auto;
}
.search_inp {
  position: relative;
  .inp {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .list {
    box-shadow: 0rpx 8rpx 10rpx 6rpx rgba(0, 0, 0, 0.3);
    width: 100%;
    left: 50%;
    transform: translateX(-50%);
    position: absolute;
    top: 80rpx;
    background-color: #ffffff;
    z-index: 999;
    padding: 20rpx;
    // height: 200rpx;
    border-radius: 16rpx;
  }
  .list_container {
    height: 200rpx;
  }
  .list_item {
    padding: 16rpx 0;
    border-bottom: 1rpx solid #eeeeee;
  }
}
</style>
